"""
银行相关业务接口
"""
from db import db_handler


# 查看余额
def check_balance_interface(username):
    user_dic = db_handler.select(username)
    return user_dic.get("balance")


# 提现功能
def withdraw_interface(username, input_money):
    user_dic = db_handler.select(username)

    out_money = int(input_money) * 1.05
    balance = user_dic.get('balance')

    if out_money > balance:
        return False, '余额不足，请重新输入！'
    else:
        user_dic['balance'] = balance - out_money
        user_dic['flow'].append(f'提现金额[{input_money}]成功 手续费[{int(input_money) * 0.05}]')
        db_handler.save(user_dic)
        return True, f'提现金额[{input_money}]成功 手续费[{int(input_money) * 0.05}]'


# 还款功能
def repay_interface(username, input_money):
    user_dic = db_handler.select(username)
    user_dic['balance'] += input_money
    user_dic['flow'].append(f'用户：[{username}] 还款[{input_money}]成功')
    db_handler.save(user_dic)

    return True, f'用户：[{username}] 还款[{input_money}]成功'


# 转账功能
def transfer_interface(username, to_user, input_money):
    user_dic = db_handler.select(username)
    to_user_dic = db_handler.select(to_user)
    if to_user_dic is None:
        return False, '目标用户不存在，请重新输入'
    if user_dic['balance'] < input_money:
        return False, '账户金额不足，请重新输入'

    user_dic['balance'] -= input_money
    to_user_dic['balance'] += input_money

    # 记录流水
    user_dic['flow'].append(f'用户[{username}] 给 目标用户[{to_user}]转账:[{input_money}]成功')
    to_user_dic['flow'].append(f'用户[{username}] 给 目标用户[{to_user}]转账:[{input_money}]成功')

    db_handler.save(user_dic)
    db_handler.save(to_user_dic)
    return True, f'用户[{username}] 给 目标用户[{to_user}]转账:[{input_money}]成功'

# 查看流水
def check_flow_interface(username):
    return db_handler.select(username)['flow']